﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Step4.Unit6.Configration.Models;
using Step4.Unit6.Configration.Options;
using System.Diagnostics;
using System.Net.NetworkInformation;

namespace Step4.Unit6.Configration.Controllers
{
    public class HomeController : Controller
    {
        /*
            ILogger 和 IConfigration 服务时系统内置服务，可随时注入，无需注册 
        */
        private readonly ILogger<HomeController> _logger;  
        private readonly IConfiguration _configuration;
        private readonly IOptions<RedisOptons> _redisOption;

        public HomeController(ILogger<HomeController> logger,
                              IConfiguration configuration,
                              IOptions<RedisOptons> redisOptions)
        {
            _logger = logger;
            _configuration = configuration;
            _redisOption = redisOptions;
        }


        // 从配置文件读取
        public IActionResult Index()
        {
            var siteName = _configuration["SiteName"].ToString();
            _logger.LogError(siteName);

            // 读取多级配置
            // ":" 冒号代表多级
            var port = _configuration["NoSQL:Redis:Port"];  
            _logger.LogError("Configration读取多级配置 NoSQL.Redis.Port:" + port);


            // 读取某个节点下所有配置
            var redisSection = _configuration.GetSection("NoSQL:Redis");
            // 通过节点对象，将配置信息导入配置类对象
            var redisOptions = redisSection.Get<RedisOptons>();
            _logger.LogInformation("获取到整个节点所有配置，并且映射到RedisOptions对象中，redisOptions.UserName:"+ redisOptions.UserName);


            // 将配置"作为服务"放在IOC容器中，
            // 通过在Program.cs 中注册IOptions<RedisOptions>服务，并将配置实例绑定到服务
            // 注入IOptions<RedisOptions>对象，直接获取到RedisOptions的实例对象，该对象中存储了redis的所有配置
            var redis = _redisOption.Value;
            
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
